<?php
	/**
	 * 登录
	 */
    class LoginIM extends APIBase {
		
		public $tag = "LoginIM";
		public $isLogin = false;
		
		
		public function before() {
			$this->initMysql();
			$this->initCacheRedis();
			$this->inithttp();
			return true;
		}
	
		public function logic() {
			
		    if(!isset($this->param['token'])){
				$this->returnError(301,'登录错误,token不能为空!');
			}
	
			$data = $this->private_decrypt($this->param['token']);
            if(empty(json_decode($data,true))){
				$this->returnError(302,'登录错误,token值有错!');
			}

			//向IM请求个人数据
			$url = 'https://demo.wgb.cn:40100/user/getMyUserInfo?imKey=ivLtTC7PmG74T9fIytiOsWTnyz4D632R';
			$userinfo = $this->http->Post($url,json_decode($data,true));
			$userinfoArr = json_decode($userinfo,true);

            if($userinfoArr['ret']==0){
				$this->returnError(303,$userinfoArr['info']['reason'].':'.$userinfoArr['info']['desc']);
			}
var_dump($userinfoArr);exit;
			//IM用户唯一id
		    $accid = $userinfoArr['info']['accid'];

			//获取ip
            $ip = $this->getRealIp();

			//判断表中是否存在该用户
			$row = $this->mysql->select("player_cs", "*", array('id' => $accid));
		    $c = count($row);
			
			//若不存在
			if($c==0){
			    $where_ip = array('register_ip' => trim($ip));
				$ipdata = $this->mysql->select("player_cs", "COUNT(*) AS `count`", $where_ip);
				if ($ipdata[0]['count'] > 10) {	
					$this->returnError(304, '该设备已经超出可注册用户范围！');
				}
				$user_info = $this->AutoReg();
			
			}
			
			if (count($row) == 0) {
				$this->returnError(312, '用户名称错误！');
			} elseif (count($row) > 1) {
				$this->e("{$user} repeat");
				$this->returnError(500, "用户名称重复！");
			}

			$password = md5($this->param['password'].$row[0]['salt']);
			if ($password != $row[0]['password']) {
				$this->returnError(312, '用户密码错误！');
			}
			
			if ($row[0]['status'] == 0){
				$this->returnError(310,"用户已经被禁用！");
			}
			//验证绑带机器码
			if($row[0]['bindpuid']!=''){
				
				if(trim($this->param['puid']) != trim($row[0]['bindpuid']))
					$this->returnError(699, "登录机器绑定机器码不一致！");
				
			}
			
			
			$uid = $row[0]['id'];			 
			$this->initDataRedis($uid);		

			$isExists = $this->data_redis->exists("hu:{$uid}");
			$player = $this->data_redis->hMGet("hu:{$uid}", array('id', 'user','skey'));
			//$isExists = 0;
			if (!$isExists || $player['id']==null || $player['user'] == null) {
                //会员数据存到redis数据库
				$this->data_redis->hMset("hu:{$uid}", $row[0]);
				/*
				$games = $this->mysql->select("player_game", "*", array('user_id' => $row[0]['id']));
				if(count($games)>0){
				  foreach($games as $ga){
				   unset($ga['id']);unset($ga['user_id']);
				   $this->data_redis->hMset("hu:{$uid}:$ga[game_id]", $ga);
				  }
				}
				*/
			    
				$this->cache_redis->hincrBy("playing", "total", 1);//大厅人数
			}
			
			//判断用户是否有背包数据
			    $backpackCount = $this->cache_redis->keys("hbackpack:".$uid.":*");
			    if(count($backpackCount)<=0){//如果玩家redis不存在背包
			    //判断数据库是否有玩家背包数据
				    $result = $this->mysql->query("select * from backpack where uid =".$uid);
				    if($result){//如果数据库存在背包,则把数据库背包数据写入redis
					    $rows = array();
				        while ( $row0 = mysql_fetch_assoc($result) ) {
			                $rows[] = $row0;
		                }
						if(count($rows) >0){
				            for ($i = 0; $i < count($rows); $i++) {
		                        $r = array();
		                        $r['uid'] = (int)$rows[$i]['uid'];
		                        $r['propid'] = (int)$rows[$i]['propid'];
                                $r['count'] = (int)$rows[$i]['count'];
                                $r['createtime'] = 	(int)$rows[$i]['createtime'];
                                $r['status'] = 	(int)$rows[$i]['status'];						
		                        $this->cache_redis->hMset("hbackpack:".$uid.":".$rows[$i]['propid'],$r);
	                        }
						}
			        }
			    }
				
				//判断用户是否有邮件数据
			    $hemailbyuser = $this->cache_redis->keys("hemailbyuser:".$uid.":*");
			    if(count($hemailbyuser)<=0){//如果玩家redis不存在背包
			    //判断数据库是否有玩家背包数据
				    $result = $this->mysql->query("select * from emailbyuser where uid =".$uid);
				    if($result){//如果数据库存在背包,则把数据库背包数据写入redis
					    $rows = array();
				        while ( $row0 = mysql_fetch_assoc($result) ) {
			                $rows[] = $row0;
		                }
						if(count($rows) >0){
				            for ($i = 0; $i < count($rows); $i++) {
		                        $r = array();
		                        $r['uid'] = (int)$rows[$i]['uid'];
		                        $r['mid'] = (int)$rows[$i]['mid'];
                                $r['is_read'] = (int)$rows[$i]['is_read'];
                                $r['is_receive'] = (int)$rows[$i]['is_receive'];
                                $r['send_date'] = (int)$rows[$i]['send_date'];
                                $r['update_date'] = (int)$rows[$i]['update_date'];	
                                $r['sender'] = (string)$rows[$i]['sender'];									
		                        $this->cache_redis->hMset("hemailbyuser:".$uid.":".$rows[$i]['id'],$r);
	                        }
						}
			        }
			    }
				
			

			
			//判断是否要弹出签到层
			//$this->sign_count($uid);
			
			//判断是否分享
			/*
			$row_ = $this->mysql->select("sharecount",'*',array('sid'=>$uid));
			if(empty($row_)){
				$this->data_redis->hset("hu:{$uid}", "hadinvited", 0);
			}else{
				$this->data_redis->hset("hu:{$uid}", "hadinvited", 1);
			}
			*/
			
			//$this->continuous_landing($uid);//计算连续登陆
			$salt = $this->data_redis->hGet("hu:{$uid}", 'salt');
			$now = time();

			$skey = md5($now . $salt);
			//抢登
			/*
			if($isExists){
			    $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=login&receiver='.$uid.'&param={"skey":"'.$player['skey'].'"}';
				if(!$this->http->get($url)){
				    	//$this->returnError(599, "抢登异常！");
				}
				
			} 
			*/
			//获取登录用户ip
			$ip = $this->getRealIp();
			$oldip = $this->data_redis->hGet("hu:$uid","login_ip");
			
			//Config::$logger->info($this->tag, $uid.--.$ip);
			$this->data_redis->hMset("hu:$uid", array("update_time" => $now, "heartbeat_at" => $now,"skey" => $skey, "login_ip" => $ip)); 
			$user_info = $this->data_redis->hMget("hu:$uid", array('flag','hadinvited','round_card_num','point',
					'user', 'name', 'sex', 'money', 'coin', 'skey','room_card','room_card_coop','login_days', 'is_get', 'exp',
					'password','avater_url','channel','is_vip','vip_time','signature','bindpuid','payment'
			));
		   
            
			if($oldip !=''){
			  if($oldip != $ip){
				  
				$user_info['last_ip'] = $oldip;
				  
			  }else{
				  
				$user_info['last_ip']='';  
			  }
			}else{
				
			    $user_info['last_ip']='';  
			  	
			}
			
		
			//判断vip
			if($user_info['is_vip']){
				$user_info['is_vip']=1;
			}
			/*
			if((int)$user_info['is_vip']&& time()<(int)$user_info['vip_time']){
			  
			  $remaining = ceil(((int)$user_info['vip_time']-time())/86400);
			  $user_info['remaining'] = $remaining;
			  	
			 //会员登录通知
			  $url = 'http://'.Config::$ip_server_confing['ip'].':'.Config::$ip_server_confing['myport'].'/pushsrv?action=Marquee&receiver=all&param={"user":"_'.$user_info['name'].'","type":1}';
			  if(!$this->http->get($url)){
				   // $this->returnError(599, "通知异常！");
			  }
			    
			}else{
			 //
			 /* $this->data_redis->hMset("hu:$uid",array('is_vip'=>0)); 	
			  $user_info['remaining'] = 0;
			  $user_info['is_vip'] = 0;		
			}
			*/
            $user_info['flag'] = (int) $user_info['flag'];
			$user_info['hadinvited'] = (int) $user_info['hadinvited'];
			$user_info['uid'] = (int)$uid;
			$user_info['sex'] = (int)$user_info['sex'];
			$user_info['money'] = (int)$user_info['money'];
			$user_info['coin'] = (int)$user_info['coin'];
			$user_info['room_card'] = (int)$user_info['room_card'];
			$user_info['room_card_coop'] = (int)$user_info['room_card_coop'];
			$user_info['login_days'] = (int)$user_info['login_days'];
			$user_info['is_get'] = (int)$user_info['is_get'];
			$user_info['exp'] = (int)$user_info['exp'];
			$user_info['is_vip'] = (int)$user_info['is_vip'];
			$user_info['password'] = $password;
			$user_info['signature']  =  $user_info['signature']?$user_info['signature']:'';
			$user_info['avater_url'] = $user_info['avater_url']?$user_info['avater_url']:'';
			$user_info['bindpuid'] = $user_info['bindpuid']?'true':'false';
			$user_info['channel'] = $user_info['channel'];
			$user_info['payment'] = $user_info['payment'];
			$user_info['round_card_num'] = $user_info['round_card_num'];
			$user_info['point'] = $user_info['point'];
			
			$user_info['ip'] = Config::$ip_server_confing['ip'];
			$user_info['port'] = Config::$ip_server_confing['port'];
			//$user_info['prushport'] = Config::$ip_server_confing['myport'];
			
			//$user_info['prop'] = $user_prop;
			$user_info['vip_time'] =0;
			//$vga = $this->cache_redis->hGetall("vga");
			//$user_info['upvenus'] = $vga['upvenus'];
			//$user_info['upgoods'] = $vga['upgoods'];
			//return (json_encode($user_info));
			$this->returnData($user_info);
		}
	
		/**
		 * 连续登录
		 */
		private function continuous_landing($uid) {
		//date_default_timezone_set('UTC');
		$ts = time();
		$update_time = $this->data_redis->hGet("hu:{$uid}", 'update_time');// 上次登录时间
		$login_days =  $this->data_redis->hGet("hu:{$uid}", 'login_days');
		if ($update_time <= $ts) {
			//$this->data_redis->hset("hu:{$uid}", "lottery_count", 0); //lottery times
			if ($update_time > ($ts - 86400)) {
				//$this->data_redis->hincrBy("hu:{$uid}", "login_days", 1);
				$this->data_redis->hset("hu:{$uid}", "is_get", 1);
				if((int)$login_days==7){
					$this->data_redis->hset("hu:{$uid}", "login_days", 0);
				}
			} else {
				$this->data_redis->hMset("hu:{$uid}", array("login_days" => 0, "is_get" => 0));
			}
		 }
	    }
		
	    /**
		 * 是否弹出签到层
		 */
	    private function sign_count($uid){
			$flag = 0;//不弹出签名层
			$ts = time();
		    $signlist = $this->cache_redis->hMGet("hSign:{$uid}", array('uid','is_sign','signdate'));
		    //判断是否签到过
			if(!$signlist['uid']){
				$flag = 1;
				$this->data_redis->hset("hu:{$uid}", "flag", 1);
			}else{
				//判断是否在同一天签到
				if($signlist['is_sign']){
					$flag = 0;
					$this->data_redis->hset("hu:{$uid}", "flag", 0);
				}elseif($signlist['is_sign']==0 && (strtotime(date("Y-m-d",$ts))-strtotime(date("Y-m-d",$signlist['signdate'])))/24/3600 <= 1){//判断是否连天签到
					$flag = 1;
					$this->data_redis->hset("hu:{$uid}", "flag", 1);
				}elseif($signlist['is_sign']==0 && (strtotime(date("Y-m-d",$ts))-strtotime(date("Y-m-d",$signlist['signdate'])))/24/3600 > 1){//不是连天签到
					$flag = 1;
					$this->data_redis->hset("hu:{$uid}", "flag", 1);
				}
				
			}
	    }
	   
	   
		//私钥解密
        public function private_decrypt($input) {
            $private_key = file_get_contents(__dir__ .'/IMpay/private_key.txt');	
            openssl_private_decrypt(base64_decode($input),$output,$private_key);  
            return $output;  
        }  

    	public function after() {
    		$this->deinitDataRedis();
			$this->deinitCacheRedis();
			$this->deinitMysql();
			$this->deinithttp();
		}
    }
?>
